package com.easybuy.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.easybuy.entity.Order;
import com.easybuy.entity.OrderDetail;
import com.easybuy.entity.Product;
import com.easybuy.entity.User;
import com.easybuy.entity.UserAddress;
import com.easybuy.service.OrderDetailService;
import com.easybuy.service.OrderService;
import com.easybuy.service.ProductService;
import com.easybuy.service.UserAddressService;
import com.easybuy.service.impl.OrderDetailServiceImpl;
import com.easybuy.service.impl.OrderServiceImpl;
import com.easybuy.service.impl.ProductServiceImpl;
import com.easybuy.service.impl.UserAddressServiceImpl;
import com.easybuy.util.ReturnResult;
import com.easybuy.util.ShoppingCart;
import com.easybuy.util.ShoppingCartItem;
public class CartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private ProductService productService = new ProductServiceImpl();
	
	private UserAddressService userAddressService = new UserAddressServiceImpl();
	
	private OrderService orderService = new OrderServiceImpl();
	
	private OrderDetailService orderDetailService = new OrderDetailServiceImpl();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		// 目的：一个Servlet可以处理多个请求
		String action = request.getParameter("action");
		if (action != null) {
			switch (action) {
			case "add":
				add(request,response);
				break;
				
			case "toSettlement":
				toSettlement(request,response);
				break;
			case "settlement1":
				settlement1(request,response);
				break;
			case "settlement2":
				settlement2(request,response);
				break;
			case "settlement3":
				settlement3(request,response);
				break;
			case "modCart":
				modCart(request,response);
				break;
			default:
				response.sendRedirect("404.jsp");
				break;
			}
		} else {
			response.sendRedirect("404.jsp");
		}
	}

	private void settlement3(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
		HttpSession session = request.getSession();
		
		User loginUser = (User) session.getAttribute("loginUser");
		
		//响应
		ReturnResult returnResult = new ReturnResult();
		//判断是否有库存，每个商品购买的数量 是否 小于 其库存数量
		boolean hasStock = true; //标识是否有库存
		ShoppingCart cart = getShoppingCartFromSession(request);
		Iterator<ShoppingCartItem> iterator = cart.getItems().values().iterator();
		
		while (iterator.hasNext()) {
			ShoppingCartItem shoppingCartItem = (ShoppingCartItem) iterator.next();
			
			Product product = productService.findById(shoppingCartItem.getProduct().getId());
			// 库存数量 小于 购买的数量
			if (product.getStock()<shoppingCartItem.getQuantity()) {
				returnResult.setMessage(product.getName()+"库存数量不足");
				hasStock = false;
				break;
			}
			
		}
		Order order = null;
		if (hasStock) {
			UserAddress userAddress = null;
			//地址要新增  addressId=-1
			String addressId = request.getParameter("addressId");
			if ("-1".equals(addressId)) {
				//新增
				userAddress = new UserAddress();
				String newAddress = request.getParameter("newAddress");
				String newRemark = request.getParameter("newRemark");
				userAddress.setAddress(newAddress);
				userAddress.setRemark(newRemark);
				userAddress.setUserId(loginUser.getId());
				
				int id= userAddressService.addUserAddress(userAddress);
				
				userAddress.setId(id);
			} else {
				//去数据库拿
				userAddress = userAddressService.findById(Integer.parseInt(addressId));
			}
			
			
			//创建订单
			
			order = new Order();
			
			order.setUserId(loginUser.getId());
			order.setLoginName(loginUser.getLoginName());
			order.setUserAddress(userAddress.getAddress());
			
			//生成一个订单号
			String serialNumber = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
			order.setSerialNumber(serialNumber);
			
			order.setCost(cart.getSum());
			
			order.setCreateTime(new Date());
			
			int id = orderService.add(order);
			
			order.setId(id);
			
			//创建订单详情
			iterator = cart.getItems().values().iterator();
			
			while (iterator.hasNext()) {
				ShoppingCartItem item = (ShoppingCartItem) iterator.next();
				
				OrderDetail detail = new OrderDetail();
				detail.setCost(item.getCost());
				detail.setOrderId(order.getId());
				detail.setProduct(item.getProduct());
				detail.setProductId(item.getProduct().getId());
				detail.setQuantity(item.getQuantity());
				
				orderDetailService.add(detail);
				
				//减库存
				productService.subStock(detail.getProductId(), detail.getQuantity());
				
			}
			
		}
		
		//清空购物车
		request.getSession().setAttribute("cart", null);
		
		//将订单存在request作用域
		request.setAttribute("currentOrder", order);
		
		request.getRequestDispatcher("pre/settlement/settlement3.jsp").forward(request, response);
		
//		PrintWriter out = response.getWriter();
//		String jsonStr = JSON.toJSONString(returnResult);
//		
//		out.print(jsonStr);
//		
//		out.flush();
//		out.close();
		
	}

	private void settlement2(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		
		User loginUser = (User) session.getAttribute("loginUser");
		//把当前登录的用户地址查出来，并存储到request作用域，key 为  userAddressList
		
		List<UserAddress> userAddressList = userAddressService.findByUserId(loginUser.getId());
		
		request.setAttribute("userAddressList", userAddressList);
		
		request.getRequestDispatcher("pre/settlement/settlement2.jsp").forward(request, response);
		
	}

	private void modCart(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String productId = request.getParameter("entityId");
		String quantity = request.getParameter("quantity");
		
		ShoppingCart cart = getShoppingCartFromSession(request);
		
		if(Integer.parseInt(quantity) <= 0){
			cart.getItems().remove(Integer.parseInt(productId));
			
		} else {

			//修改购物车中 某个商品的数量
			ShoppingCartItem cartItem = cart.getItems().get(Integer.parseInt(productId));
			cartItem.setQuantity(Integer.parseInt(quantity));
		}
		
		//计算购物车总金额
		cart.calSum();
		
		request.getSession().setAttribute("cart", cart);
		
		PrintWriter out = response.getWriter();
		ReturnResult result = new ReturnResult();
		result.setMessage("操作成功");
		result.setStatus(1);
		
		String jsonStr = JSON.toJSONString(result);
		
		out.print(jsonStr);
		
		out.flush();
		out.close();
	}

	private void settlement1(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("pre/settlement/settlement1.jsp").forward(request, response);
		
	}

	private void toSettlement(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.getRequestDispatcher("pre/settlement/toSettlement.jsp").forward(request, response);
	}

	private void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		
		//获取参数
		int productId =Integer.parseInt(request.getParameter("entityId"));
		int quantity = Integer.parseInt(request.getParameter("quantity"));
		
		//获取product
		Product product = productService.findById(productId);
		
		//选中了一个商品，要放到购物车
		//要拿购物车，在session里，（如果session里没有就得创建一个）
		HttpSession session = request.getSession();
		ShoppingCart cart = getShoppingCartFromSession(request);
		
		//将商品放入购物车（计算总额）
		cart.addItem(product, quantity);
		
		session.setAttribute("cart", cart);
		//响应
		ReturnResult result = new ReturnResult(1,"已加入购物车");
		
		String jsonStr = JSON.toJSONString(result);
		
		out.print(jsonStr);
		
		out.flush();
		out.close();
	}
	
	private ShoppingCart getShoppingCartFromSession(HttpServletRequest request){
		HttpSession session = request.getSession();
		ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
		
		if (cart == null) {
			cart = new ShoppingCart();
		}
		return cart;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
